import React, { Component } from 'react';
import { connect } from 'dva';
import * as Cesium from 'cesium';
import NAMESPACE from '~/constants/namespace';
import 'cesium/Build/Cesium/Widgets/widgets.css';
import { GET_ENGINEER_LIST, SAVE_CURR_ENGINEER } from '~/constants/effects';
import './index.less';

@connect(state => ({
  engineerList: state[NAMESPACE.PROJECT_MANAGE].engineerList
}))
export default class IndexPage extends Component {

  constructor (props) {
    super(props);
    this.pitchValue = -30;
    this.currEngIndex = 0;
    this.state = {
      shouldAnimate: true,
      markData: []
    }
  }

  componentDidMount () {

    this.props.dispatch({
      type: GET_ENGINEER_LIST
    }).then(() => {
      let markData = [];
      const engineeringList = this.props.engineerList;
      this.saveEngineering(engineeringList[0].id);
      engineeringList.forEach(item => {
        item.height = 4000;
        item.top = 0;
        item.left = 0;
        item.wht = 0;
        item.cht = 0;
        if (item.latitude) {
          markData.push(item);
        }
      });
      this.setState({ markData });
      setTimeout(() => this.mapInit() , 0);
    })

  }

  /**
   * 保存当前浏览的工程
   */
  saveEngineering(engineeringId) {
    this.props.dispatch({
      type: SAVE_CURR_ENGINEER,
      payload: {
        engineeringId
      }
    })
  }

  /**
   * 影像初始化
   */
  mapInit () {
    Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwNGVhZGZjYy03Y2U2LTQwZTgtYmU4NS01NGJjMTIzNGVlYTkiLCJpZCI6NTYwNjgsImlhdCI6MTYyMTIzMTE3OH0.i1xW4qhmf-6wsBO6lxqwFhmj-OTCIyfOT4N2z6wZjlc';
    //默认使用高德在线影像
    const base = new Cesium.UrlTemplateImageryProvider({
      url : 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
      tilingScheme : new Cesium.WebMercatorTilingScheme(),
      maximumLevel : 100
    });

    this.viewer = new Cesium.Viewer('cesiumContainer', {
      animation:false,
      fullscreenButton:false,
      vrButton:false,
      geocoder:false,
      homeButton:false,
      timeline:false,
      sceneModePicker:false,
      baseLayerPicker:false,
      navigationHelpButton:false,
      selectionIndicator : false,
      imageryProvider: base
      // imageryProvider: new Cesium.UrlTemplateImageryProvider({
      //   url: 'http://172.30.34.92:8080/wapian/{z}/{x}/{y}.png',
      //   fileExtension: 'png'
      // })
    });
    this.viewer.cesiumWidget.creditContainer.style.display = "none";
    this.viewer.bottomContainer.style.display = "none";

    const markData = this.state.markData;

    // 初始化飞行坐标
    this.viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(markData[0].longitude, markData[0].latitude, 4000),
      duration: 5,
      orientation: {
        pitch: Cesium.Math.toRadians(this.pitchValue)
      }
    });

    //初始化工程位置和视角效果
    this.startInit();

    //改善实体的文字和图片清晰度
    this.viewer.scene.fxaa = false;
    //降低性能提供图片质量
    this.viewer.scene.globe.maximumScreenSpaceError = 4/3;
    //改变地图灰度系数
    let layer0 = this.viewer.scene.imageryLayers.get(0);
    layer0.gamma = 0.66;

    // 亮度设置
    const stages = this.viewer.scene.postProcessStages;
    this.viewer.scene.brightness =  this.viewer.scene.brightness || stages.add(Cesium.PostProcessStageLibrary.createBrightnessStage());
    this.viewer.scene.brightness.enabled = true;
    this.viewer.scene.brightness.uniforms.brightness = Number(1.5);

    const handler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas);
    // 鼠标左键按下事件
    handler.setInputAction((event) => {
      this.setState({ shouldAnimate: false });
      this.viewer.clock.shouldAnimate = false;
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

    // 鼠标左键抬起事件
    handler.setInputAction((event) => {
      this.setState({ shouldAnimate: true });
      this.viewer.clock.shouldAnimate = true;
      switch (this.state.currIndex) {
        case 1: this.step1(); break;
        case 2: this.step2(); break;
        case 3: this.step3(); break;
        case 4: this.step4(); break;
        default: break;
      }
    }, Cesium.ScreenSpaceEventType.LEFT_UP);
  }

  /**
   * 初始化视角
   */
  startInit () {
    setTimeout(() => {
      //坐标上插如图片
      for (let i = 0; i< this.state.markData.length; i++) {
        this.addSiteIcon(this.viewer, this.state.markData[i])
      }
      this.startCurrEngTo(this.viewer, 1000);
    },3000);
  }

  /**
   * 原地旋转
   * @param viewer
   * @param obj
   */
  cameraRotate(viewer, obj, ms, callback) {
    if (!this.state.suspend) {
      // 相机看点的角度，如果大于0那么则是从地底往上看，所以要为负值，这里取-30度
      const pitch = Cesium.Math.toRadians(this.pitchValue);
      // 给定飞行一周所需时间，比如10s, 那么每秒转动度数
      const angle = 360 / ms;
      const startTime = Cesium.JulianDate.fromDate(new Date());

      const stopTime = Cesium.JulianDate.addSeconds(startTime, ms, new Cesium.JulianDate());

      viewer.clock.startTime = startTime.clone();  // 开始时间
      viewer.clock.stopTime = stopTime.clone();     // 结速时间
      viewer.clock.currentTime = startTime.clone(); // 当前时间
      viewer.clock.clockRange = Cesium.ClockRange.CLAMPED; // 行为方式
      viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK; // 时钟设置为当前系统时间; 忽略所有其他设置。

      // 相机的当前heading
      const initialHeading = viewer.camera.heading;
      this.Exection = () => {
        // 当前已经过去的时间，单位
        const delTime = Cesium.JulianDate.secondsDifference(viewer.clock.currentTime, viewer.clock.startTime);
        const heading = Cesium.Math.toRadians(delTime * angle) + initialHeading;
        viewer.scene.camera.setView({
          destination: Cesium.Cartesian3.fromDegrees(obj.longitude, obj.latitude, obj.height),
          orientation: {
            heading: heading,
            pitch: pitch
          }
        });

        if (Cesium.JulianDate.compare(viewer.clock.currentTime, viewer.clock.stopTime) >= 0) {
          viewer.clock.onTick.removeEventListener(this.Exection);
          viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(obj.longitude, obj.latitude, obj.height),
            duration: 5,
            complete: () => {
              callback();
            }
          });
        }
      };

      viewer.clock.onTick.addEventListener(this.Exection);
    }
  }

  /**
   * 开始下一个工程
   * @param viewer
   * @param timer
   */
  startCurrEngTo(viewer, timer) {
    setTimeout (() => {
      this.step1();
    }, timer)
  }

  /**
   * 相机随工程移动
   */
  cameraCurrEngTo(viewer) {
    this.setState({ currIndex: 1 });
    if (!this.state.shouldAnimate) {
      return;
    }
    const obj = this.state.markData[this.currEngIndex];
    if (obj) {
      this.currObj = obj;
      this.saveEngineering(obj.id);
      viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(obj.longitude, obj.latitude, obj.height),
        duration: 3,
        complete: () => {
          this.setState({ currIndex: 2 });
          if (!this.state.shouldAnimate) {
            return;
          }
          this.step2();
        }
      });
    } else {
      this.currEngIndex = 0;
      this.startCurrEngTo (viewer, 5000);
    }
  }


  /**
   * 飞到当前工程后，相机拉近
   * @param viewer
   * @param obj
   * @param callback
   */
  cameraZoomIn(viewer, obj, callback) {
    const height = 3000;
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(obj.longitude, obj.latitude, height),
      duration: 5,
      complete: () => {
        setTimeout(() => {
          const newObj = JSON.parse(JSON.stringify(obj));
          callback(newObj);
        }, 5000)
      }
    });
  }

  /**
   * 进入下一个工程,
   * */
  step1 () {
    this.cameraCurrEngTo(this.viewer);
  }

  step2 () {
    const obj = this.currObj;
    this.cameraZoomIn(this.viewer, obj, () => {
      this.setState({ currIndex: 3 });
      if (!this.state.shouldAnimate) {
        return;
      }
      this.step3();
    });
  }

  step3 () {
    const obj = this.currObj;
    const pitch = Cesium.Math.toRadians(this.pitchValue);
    this.viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(obj.longitude, obj.latitude, obj.height),
      duration: 3,
      orientation: {
        pitch: pitch
      },
      complete: () => {
        this.setState({ currIndex: 4 });
        if (!this.state.shouldAnimate) {
          return;
        }
        this.step4();
      }
    });
  }

  step4 () {
    this.currEngIndex++;
    this.startCurrEngTo(this.viewer, 10000);
  }



  //插入图片
  addSiteIcon(viewer, obj) {
    const markData = this.state.markData;
    const scratch = new Cesium.Cartesian2();
    const that = this;
    viewer.scene.preRender.addEventListener(function() {
      const position = Cesium.Cartesian3.fromDegrees(obj.longitude,obj.latitude, -10);
      const canvasPosition = viewer.scene.cartesianToCanvasCoordinates(position, scratch);
      if (Cesium.defined(canvasPosition)) {
        markData.forEach(item => {
          if (item.id === obj.id) {
            const cht = document.getElementById(`sp-${obj.id}`).clientHeight;
            const wht = document.getElementById(`sp-${obj.id}`).clientWidth;
            item.top = canvasPosition.y;
            item.left = canvasPosition.x;
            item.cht = cht;
            item.wht = wht;
            that.setState({ markData });
          }
        })
      }
    });
  }

  render () {
    return (
      <div
        className="home-warp"
        style={{ position: 'relative', width: document.body.clientWidth, height: document.documentElement.clientHeight, overflow: 'hidden'}}
      >
        <div
          id="cesiumContainer"
          style={{ position: 'absolute', top: 0, left:0, zIndex: 1, width: document.body.clientWidth, height: '100%', overflow: 'hidden'}}></div>
        {
          this.state.markData?.map((item, index) =>
            <div
              key={index}
              className="modular"
              onClick={() => console.log('----')}
            >
              <div
                id={`sp-${item.id}`}
                className="modular-children"
                style={{ top: item.top - (item.cht ? item.cht : 0), left: item.left - (item.wht ? item.wht/2 - 10 : 0) }}
              >
                <div className="pro-name">
                  <div className="value">{item.name}</div>
                </div>
                <div className="line">建设单位：{item.developmentOrganization}</div>
                <div className="line">总人数：{item.headcount}人</div>
                {/*<span className="arrow-bottom"></span>*/}
                {/*<img src={require('~/static/arrow_bottom.png')} alt="" className="arrow-bottom" />*/}
              </div>
              <img
                alt=""
                width={20}
                height={41}
                style={{ position: 'absolute', top: item.top, left: item.left, zIndex: 2 }}
                src={require('~/static/site_icon.png')}
              />
            </div>
          )
        }
        {/*<span*/}
        {/*  style={{ position: 'absolute', top: 120, zIndex: 2, right: '30%', color: '#fff', display: 'inline-block', cursor: 'pointer'}}*/}
        {/*  onClick={() => this.onSuspend()}*/}
        {/*>{this.state.suspend ? <img src={require('src/static/play.png').default} width={95} alt="" /> :*/}
        {/*  <img src={require('src/static/stop.png').default} width={95} alt="" />}</span>*/}
      </div>
    )
  }
}
